package com.uhb.base.util;

import com.feidee.data.report.util.JsonUtil;
import com.uhb.base.exception.RequestParamInvalidJsonException;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

public class ControllerPointCut {

	private static Logger logger = Logger.getLogger(ControllerPointCut.class);

	public void init(JoinPoint jp) throws SQLException {
	    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	    System.setProperty ("WORKDIR", request.getSession().getServletContext().getRealPath("/"));
		Object[] obs = jp.getArgs();
		for (Object ob : obs) {
			if (ob instanceof BindingResult) {
				BindingResult bindingResult = (BindingResult) ob;
				if (bindingResult.hasErrors()) {
					request.setAttribute("err", bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage());
					logger.error(bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage());
					logger.error("Parameters:" + JsonUtil.map2JsonStr(request.getParameterMap()));
					throw new RequestParamInvalidJsonException(bindingResult.getFieldError());
				}
			}
		}
		// 增加其他所有controller方法执行前的初始化代码.
	}
}